import React , { Component }from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchPosts } from '../actions/index';
import { Link } from 'react-router';

class PostsIndex extends Component {
  constructor(props) {
    super(props);

    console.log(props);
  }
  componentWillMount() {
    this.props.fetchPosts();
  }

  renderItems() {

    if(!this.props.posts.length) {
      return (
        <article>
          正在加载中...
        </article>
      )
    }
    return this.props.posts.map( (post) => {
      return (
        <Link to={`/posts/${post.id}`} className="list-group-item" key={post.id}>
          <span className="pull-xs-right">{ post.categories }</span>
          <strong>{ post.title }</strong>
        </Link>
      )
    })
  }

  render() {
    return (
      <div>
        <div className="text-xs-right">
          <Link to="/posts/new" className="btn btn-primary">
            Add a posts.
          </Link>
        </div>
        <h1>List of blog posts</h1>
        <div className="list-group">
          { this.renderItems() }
        </div>
      </div>
    )
  }
}


function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    fetchPosts
  }, dispatch);
}

function mapStateToProps(state) {
  return {
    posts: state.posts.all
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(PostsIndex);
